# coding=UTF-8
from django.db import models
from django.utils.translation import gettext_lazy as _
from django.contrib.auth.models import User
# http://www.djangoproject.com/documentation/models/generic_relations/
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generic

class FavouriteItem(models.Model):
    user = models.ForeignKey(User, verbose_name=_('Usuario'))
    content_type = models.ForeignKey(ContentType)
    object_id = models.PositiveIntegerField()
    object = generic.GenericForeignKey('content_type', 'object_id')

    def is_product(self):
        if not self.object:
            return False
        if self.object.__class__.__name__ == 'Product':
            ctype = ContentType.objects.get_for_model(self.object)
            return (self.content_type == ctype)
        else:
            print self.object.__class__.__name__

    def __unicode__(self):
        if not self.object:
            return ''
        return _('Favorito: %s') % (self.object)

    def save(self):
        if not self.id:
            try:
                favourite = FavouriteTop.objects.get(
                    content_type=self.content_type,
                    object_id=self.object_id)
            except FavouriteTop.DoesNotExist:
                favourite = FavouriteTop(
                    content_type=self.content_type,
                    object_id=self.object_id)
            favourite.how_many += 1
            favourite.save()
        super(FavouriteItem, self).save()

    def delete(self):
        try:
            favourite = FavouriteTop.objects.get(
                content_type=self.content_type,
                object_id=self.object_id)
            if favourite.how_many > 1:
                favourite.how_many -= 1
                favourite.save()
            else:
                favourite.delete()
        except FavouriteTop.DoesNotExist:
            pass
        super(FavouriteItem, self).delete()

class FavouriteTop(models.Model):
    content_type = models.ForeignKey(ContentType)
    object_id = models.PositiveIntegerField()
    object = generic.GenericForeignKey('content_type', 'object_id')
    how_many = models.PositiveIntegerField(_('¿Cuántos?'), default=0)

    def is_product(self):
        if not self.object:
            return False
        if self.object.__class__.__name__ == 'Product':
            ctype = ContentType.objects.get_for_model(self.object)
            return (self.content_type == ctype)

    def __unicode__(self):
        return "%i %s" % (self.how_many, self.object)

